<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>编辑Token</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
    <style>
        .mainBox { padding: 15px; }
        .main-container { max-width: 800px; margin: 0 auto; }
        .layui-form-item { margin-bottom: 20px; }
        .bottom { position: fixed; bottom: 0; left: 0; right: 0; padding: 15px; 
                  background: #fff; box-shadow: 0 -2px 10px rgba(0,0,0,0.05); }
        .button-container { text-align: center; }
        .button-container button { margin: 0 8px; }
    </style>
</head>

<body>
    <form class="layui-form" action="" lay-filter="token-edit">
        <div class="mainBox">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required" autocomplete="off"
                            placeholder="请输入Token名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">允许IP</label>
                    <div class="layui-input-block">
                        <!-- <input type="text" name="allowed_ips" id="allowed_ips" lay-verify="verifyIP" autocomplete="off"
                            placeholder="请输入允许IP（多个用逗号分隔，*表示所有）" class="layui-input"> -->
                        <textarea name="allowed_ips" id="allowed_ips" placeholder="请输入允许IP（多个用逗号分隔，*表示所有）"
                            lay-verify="verifyIP" class="layui-textarea">*</textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用途说明</label>
                    <div class="layui-input-block">
                        <textarea name="description" id="description" placeholder="请输入Token用途说明" class="layui-textarea" rows="3"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="启用" lay-skin="tag" checked>
                        <input type="radio" name="is_active" value="0" title="禁用" lay-skin="tag">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">过期时间</label>
                    <div class="layui-input-block">
                        <input type="text" name="expires_time" id="expires_time" autocomplete="off"
                            placeholder="请选择过期时间（留空表示永久）" class="layui-input" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" name="sort_num" id="sort_num" lay-verify="verifySort" autocomplete="off"
                            placeholder="请输入排序号（默认0）" class="layui-input" value="0">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">Token预览</label>
                    <div class="layui-input-block">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span id="token-preview" style="flex: 1; font-family: monospace; letter-spacing: 2px; 
                                background: #f5f5f5; padding: 8px 12px; border-radius: 3px; border: 1px solid #e0e0e0;
                                overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                ••••••••••••••
                            </span>
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" id="toggle-token" title="显示Token">
                                <i class="layui-icon layui-icon-password"></i>
                            </button>
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-primary" id="copy-token" title="复制Token">
                                <i class="layui-icon layui-icon-file"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit lay-filter="token-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <!-- <button type="reset" class="pear-btn pear-btn-sm" id="reset-btn">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button> -->
                <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" id="close-btn">
                    <i class="layui-icon layui-icon-close"></i>
                    关闭
                </button>
            </div>
        </div>
    </form>

    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'layer', 'laydate'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let layer = layui.layer;
            let laydate = layui.laydate;

            // 全局配置
            const API_BASE_URL = apiConfig.baseUrl;
            const AUTH_TOKEN = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");
            const urlParams = new URLSearchParams(window.location.search);
            const TOKEN_ID = urlParams.get('id');
            let initialData = {};
            let isTokenVisible = false;
            let currentToken = '';

            // 初始化日期选择器
            laydate.render({
                elem: '#expires_time',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                min: new Date().getTime() + 60 * 1000, // 最小时间为当前时间+1分钟
                btns: ['clear', 'confirm'],
                theme: '#1E9FFF',
                done: function(value) {
                    if (value) $('#expires_time').val(value);
                }
            });

            // 表单验证规则
            form.verify({
                verifySort: function (value) {
                    if (value === '') return "排序号不能为空！";
                    if (!/^\d+$/.test(value)) return "排序号必须为非负整数！";
                    if (parseInt(value) > 9999) return "排序号最大为9999！";
                },
                verifyIP: function (value) {
                    if (value === '') return "允许IP不能为空！请输入*或具体IP";
                    if (value === "*") return true;

                    const ips = value.split(',').map(ip => ip.trim());
                    const ipReg = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
                    
                    for (let ip of ips) {
                        if (!ip) return "IP列表不能包含空值！";
                        if (!ipReg.test(ip)) return `IP格式错误：${ip}（正确格式如192.168.1.1）`;
                    }
                }
            });

            // Token显示/隐藏切换
            $('#toggle-token').on('click', function() {
                if (!currentToken) {
                    layer.msg('Token未加载或为空', { icon: 2, time: 1500 });
                    return;
                }
                
                isTokenVisible = !isTokenVisible;
                const $icon = $(this).find('i');
                const $preview = $('#token-preview');

                if (isTokenVisible) {
                    $preview.text(currentToken);
                    $icon.removeClass('layui-icon-password').addClass('layui-icon-close');
                    $(this).attr('title', '隐藏Token');
                } else {
                    $preview.text('•••••••••••••');
                    $icon.removeClass('layui-icon-close').addClass('layui-icon-password');
                    $(this).attr('title', '显示Token');
                }
            });

            // Token复制功能
            $('#copy-token').on('click', function() {
                if (!currentToken) {
                    layer.msg('Token未加载或为空', { icon: 2, time: 1500 });
                    return;
                }

                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(currentToken)
                        .then(() => layer.msg('Token已复制到剪贴板', { icon: 1, time: 1500 }))
                        .catch(err => {
                            console.error('Clipboard API失败：', err);
                            fallbackCopyToken();
                        });
                } else {
                    fallbackCopyToken();
                }
            });

            // 复制Token降级方案
            function fallbackCopyToken() {
                const textarea = document.createElement('textarea');
                textarea.value = currentToken;
                textarea.style.position = 'fixed';
                textarea.style.left = '-9999px';
                textarea.style.top = '-9999px';
                document.body.appendChild(textarea);
                
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                
                layer.msg('Token已复制到剪贴板', { icon: 1, time: 1500 });
            }

            // 加载Token详情数据
            function loadTokenData() {
                if (!TOKEN_ID) {
                    layer.msg('Token ID不存在，无法加载数据', { icon: 2, time: 2000 });
                    return;
                }

                const loading = layer.load(2, { shade: 0.3 });
                $.ajax({
                    url: `${API_BASE_URL}/common/token/${TOKEN_ID}/`,
                    dataType: 'json',
                    type: 'GET',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success && result.data) {
                            const data = result.data;
                            currentToken = data.access_token || ''; // 关键修复：使用access_token字段
                            
                            // 保存初始数据
                            initialData = {
                                name: data.name || '',
                                allowed_ips: data.allowed_ips || '',
                                description: data.description || '',
                                is_active: data.is_active.toString() || '1',
                                expires_time: formatDateToFront(data.expires_time) || '',
                                sort_num: data.sort_num.toString() || '0'
                            };

                            // 渲染表单数据
                            form.val("token-edit", initialData);
                        } else {
                            const errorMsg = result.message || '加载Token数据失败';
                            layer.msg(errorMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401 ? '登录已过期，请重新登录' : '网络异常，加载失败';
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });
            }

            // 日期格式转换：后端→前端
            function formatDateToFront(dateStr) {
                if (!dateStr) return '';
                try {
                    const date = new Date(dateStr);
                    const pad = num => num.toString().padStart(2, '0');
                    return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
                } catch (err) {
                    return '';
                }
            }

            // 日期格式转换：前端→后端
            function formatDateToBackend(dateStr) {
                if (!dateStr) return null;
                try {
                    const date = new Date(dateStr);
                    return date.toISOString();
                } catch (err) {
                    return null;
                }
            }

            // 判断数据是否修改
            function isDataChanged(currentData) {
                const compareFields = ['name', 'allowed_ips', 'description', 'is_active', 'expires_time', 'sort_num'];
                for (let field of compareFields) {
                    if (field === 'expires_time') {
                        const current = currentData[field].trim();
                        const initial = initialData[field].trim();
                        if (current !== initial) return true;
                    } else {
                        if (currentData[field] !== initialData[field]) return true;
                    }
                }
                return false;
            }

            // 表单提交（更新Token）
            form.on('submit(token-save)', function (data) {
                const currentData = data.field;

                if (!isDataChanged(currentData)) {
                    layer.msg("未修改任何数据，无需提交", { icon: 3, time: 1500 });
                    return false;
                }

                const submitData = {
                    ...currentData,
                    expires_time: formatDateToBackend(currentData.expires_time),
                    sort_num: parseInt(currentData.sort_num)
                };

                const loading = layer.load(2, { shade: 0.3 });
                $.ajax({
                    url: `${API_BASE_URL}/common/token/${TOKEN_ID}/`,
                    data: JSON.stringify(submitData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'PATCH',
                    headers: { "Authorization": AUTH_TOKEN },
                    success: function (result) {
                        layer.close(loading);
                        if (result.success) {
                            layer.msg(result.message || '更新成功', {
                                icon: 1,
                                time: 1500
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table");
                            });
                        } else {
                            const errorMsg = result.message || '更新失败';
                            if (result.data && typeof result.data === 'object') {
                                const firstError = Object.values(result.data)[0];
                                layer.msg(firstError || errorMsg, { icon: 2, time: 2000 });
                            } else {
                                layer.msg(errorMsg, { icon: 2, time: 2000 });
                            }
                        }
                    },
                    error: function (xhr) {
                        layer.close(loading);
                        const errorMsg = xhr.status === 401 ? '登录已过期，请重新登录' : '网络异常，更新失败';
                        layer.msg(errorMsg, { icon: 2, time: 2000 });
                        if (xhr.status === 401) parent.window.location.href = '../../../login.html';
                    }
                });

                return false;
            });

            // 重置按钮事件
            $('#reset-btn').on('click', function() {
                // 重置为初始数据（而非清空）
                form.val("token-edit", initialData);
                layer.msg('已重置为原始数据', { icon: 0, time: 1000 });
            });

            // 关闭按钮事件
            $('#close-btn').on('click', function() {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            // 页面加载时初始化数据
            loadTokenData();
        });
    </script>
</body>
</html>